#include"../include/lib_headers.h"

char* unmount_vfs(char *vfs_path) {
	int i=0;
	
	/* Insufficient Arguments */
	if(strlen(vfs_path) == 0){
		sprintf(output_message,"%s %s","unmountvfs_FAILURE",ERR_VFS_UNMOUNT_00);	
		return output_message;
	}
	
	/* VFS Not Mounted */
	if (h==NULL || l1 == NULL || strcmp(vfs_path,h->VFS_Label)!=0) {
		sprintf(output_message,"%s %s","unmountvfs_FAILURE",ERR_VFS_UNMOUNT_03);
		return output_message;
	}

	/* Data File Not Found */
	FILE *fp = fopen(vfs_path, "rb+");
	if(fp==NULL){
		sprintf(output_message,"%s %s","unmountvfs_FAILURE",ERR_VFS_UNMOUNT_01);	
		return output_message;
	}	
	
	
	if(l1->next == NULL){
		/* cannot write to datafile */
		if(fwrite(h,sizeof(hd),1,fp)!=1){
			sprintf(output_message,"%s %s","unmountvfs_FAILURE",ERR_VFS_UNMOUNT_02);	
			return output_message;
		}
		array=(fd*)malloc(sizeof(fd)*h->maxFds);
		/* cannot write to datafile */
		if(fwrite(array,sizeof(fd), h->maxFds, fp)<1){
			sprintf(output_message,"%s %s","unmountvfs_FAILURE",ERR_VFS_UNMOUNT_02);	
			return output_message;
		}
		freelist=(int*)calloc(sizeof(int),h->maxFds);
		/* cannot write to datafile */
		if(fwrite(freelist,sizeof(int), h->maxFds,fp)<1){
			sprintf(output_message,"%s %s","unmountvfs_FAILURE",ERR_VFS_UNMOUNT_02);	
			return output_message;
		}
		
	}	
	else {
		cnt=0;	
		traverse_write(l1->next);
		cnt=0;	
		/* cannot write to datafile */		
		if(fwrite(h,sizeof(hd),1,fp) != 1){
			sprintf(output_message,"%s %s","unmountvfs_FAILURE",ERR_VFS_UNMOUNT_02);	
			return output_message;
		}
		/* cannot write to datafile */
		if(fwrite(array,sizeof(fd), h->maxFds, fp) < 1){
			sprintf(output_message,"%s %s","unmountvfs_FAILURE",ERR_VFS_UNMOUNT_02);	
			return output_message;
		}
		/* cannot write to datafile */
		if(fwrite(freelist,sizeof(int), h->maxFds,fp) < 1){
			sprintf(output_message,"%s %s","unmountvfs_FAILURE",ERR_VFS_UNMOUNT_02);	
			return output_message;
		}
	}
	if(l1 != NULL)
		unmount_nAry(l1->next);
	if(bstRoot != NULL)	
		unmount_bst(bstRoot);

	unmount_hashTable(hashtable);
	
	free(freelist);
	free(array);
	free(h);
	h=NULL;	
	l1=NULL;
	hashtable=NULL;
	bstRoot=NULL;
	array=NULL;
	freelist = NULL;
	fclose(fp);
	sprintf(output_message,"%s","unmountvfs_SUCCESS");	
	return output_message;
}

